package edu.suda.basic;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

public class POITest
{
	private static void adjustColumnsSize(Sheet sheet)
	{
		Iterator<Row> rowPtr=sheet.iterator();
		int rowSize=rowPtr.next().getLastCellNum();
		String tmpStr="";
		for(int i=0;i<rowSize;i++)
		{
			rowPtr=sheet.iterator();
			while(rowPtr.hasNext())
			{
				tmpStr=rowPtr.next().getCell(i).toString();
				if(sheet.getColumnWidth(i)<256*Record.calcStrWidth(tmpStr))
				{
					sheet.setColumnWidth(i, 256*Record.calcStrWidth(tmpStr));
				}
			}
		}
	}

	public static void main(String args[])
	{
		File outputFile = null;
		FileOutputStream fos = null;
		HSSFWorkbook workbook = null;
		HSSFSheet sheet = null;
		HSSFRow row = null;
		HSSFCell cell = null;
		Record[] instances;
		instances = new Record[4];

		try
		{
			outputFile = new File("D:\\Test.xls");
			fos = new FileOutputStream(outputFile);

			workbook = new HSSFWorkbook();
			sheet = workbook.createSheet("Column Test.");

			String[] titles = { "审核状态", "审核日期", "户主姓名", "姓名", "性别", "身份证号码",
					"救助证书号", "救助对象类别", "地址" };
			instances[0] = new Record("审核通过", "2012-12-02", "吴帧化", "吴帧化", "男",
					"532926198602232074", "TH_csdblxel", " ", "安徽省安庆市太湖县江塘乡小宫村");
			instances[1] = new Record("审核通过", "2012-12-02", "李四", "李四", "男",
					"340825198804051037", "", "Th-01-01", "安徽省安庆市太湖县江塘乡小宫村");
			instances[2] = new Record("初始/未审核", "", "张杰", "张杰", "",
					"310106197301253975", "", "", "安徽省安庆市潜山县槎水镇");
			instances[3] = new Record("审核通过", "2012-12-01", "张三	", "张三", "男",
					"340825198604061038", "", "0101", "安徽省安庆市潜山县塔畈乡西河村");

			row = sheet.createRow(0);
			for (int i = 0; i < titles.length; i++)
			{
				cell = row.createCell(i);
				cell.setCellValue(titles[i]);
				sheet.setColumnWidth(i, 256 * Record.calcStrWidth(titles[i]));
			}

			for (int i = 0; i < instances.length; i++)
			{
				row = sheet.createRow(i + 1);
				instances[i].map2ExcelColumn(row);
			}
			adjustColumnsSize(sheet);
			workbook.write(fos);
		}
		catch (IOException ioEx)
		{
			System.out.println("Caught an: " + ioEx.getClass().getName());
			System.out.println("Message: " + ioEx.getMessage());
			System.out.println("Stacktrace follows:.....");
			ioEx.printStackTrace(System.out);
		}
		finally
		{
			if (fos != null)
			{
				try
				{
					fos.close();
				}
				catch (IOException ioEx)
				{
					// Ignore - too late to recover anything now.
					ioEx.printStackTrace();
				}
			}
		}
	}
}
